#入口文件
from flask_script import Manager
from whbbs import create_app
from exts import db
from flask_migrate import Migrate,MigrateCommand
from apps.cms import models as cms_models
CMSUser = cms_models.CMSUser
CMSRole = cms_models.CMSRole
CMSPermission = cms_models.CMSPermission
app = create_app()
manager = Manager(app)

Migrate(app,db)
manager.add_command('db',MigrateCommand)

@manager.option('-u','--username',dest='username')
@manager.option('-p','--password',dest='password')
@manager.option('-e','--email',dest='email')

def create_cms_user(username,password,email):
    user = CMSUser(username=username,password=password,email=email)
    db.session.add(user)
    db.session.commit()
    print("cms用户添加成功")

@manager.option('-e','--email',dest='email')
@manager.option('-n','--name',dest='name')
def add_user_to_role(email,name):
    user = CMSUser.query.filter_by(email=email).first()
    if user:
        role = CMSRole.query.filter_by(name=name).first()
        if role:
            role.users.append(user)
            db.session.commit()
            print("将%s用户添加到%s角色成功"%(email,name))
        else:
            print("没有%s角色" % name)
    else:
        print("没有%s邮箱"%email)


@manager.command
def create_role():
    #1访问者 只能修改个人信息
    visitor = CMSRole(name="访问者",desc="只能修改个人信息，其它查看不能修改")
    visitor.permissions = CMSPermission.VISITOR
    #运营者  帖子、评论、个人信息、前台用户
    operator = CMSRole(name="运营人员",desc="帖子、评论、个人信息、前台用户管理")
    operator.permissions = CMSPermission.VISITOR|CMSPermission.POSTER|CMSPermission.COMMENTER|CMSPermission.FRONTUSER|CMSPermission.BOARDER
    #管理员 拥有本系统所有的权限
    admin =  CMSRole(name="管理人员",desc="本系统所有权限")
    admin.permissions = CMSPermission.VISITOR|CMSPermission.POSTER|CMSPermission.COMMENTER|CMSPermission.FRONTUSER|CMSPermission.CMSUSER|CMSPermission.BOARDER
    developer =  CMSRole(name="开发者",desc="开发人员专用")
    developer.permissions = CMSPermission.ALL_PERMISSION

    db.session.add_all([visitor,operator,admin,developer])
    db.session.commit()

@manager.command
def test_permission():
    user = CMSUser.query.filter_by(email='developer@163.com').first()
    # if user.has_permission(CMSPermission.VISITOR):
    if user.is_developer:
        print("是开发者")
    else:
        print("不是开发者")

if __name__ == "__main__":
    manager.run()